package utils;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public static void post(String url, String token, String str) throws Exception{


        // 创建URL对象
        URL obj = new URL(url);

        // 打开连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 设置请求头
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Cookie", token);

        // 可选：设置超时时间
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        // 设置POST请求可用
        con.setDoOutput(true);

        // 发送POST请求
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(str);
            wr.flush();
        }

        // 获取响应代码
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        // 读取响应内容
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            System.out.println("Response Body : " + response.toString());
        }

    }

    public static void main(String[] args) throws Exception {

        // 目标URL
        String url = "http://example.com/api/endpoint";

        // 创建URL对象
        URL obj = new URL(url);

        // 打开连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 设置请求头
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer your_access_token");

        // 可选：设置超时时间
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        // 设置POST请求可用
        con.setDoOutput(true);

        // 构建请求体数据（如果有）
        String postData = "{\"key1\": \"value1\", \"key2\": \"value2\"}";

        // 发送POST请求
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(postData);
            wr.flush();
        }

        // 获取响应代码
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        // 读取响应内容
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            System.out.println("Response Body : " + response.toString());
        }
    }
}
